/**
 @文件名： router/index.ts
 @来源：YongPing.Wang|2023/11/12 11:12
 @描述：路由
 **/
import { createRouter, createWebHistory, type NavigationGuardNext, type RouteLocationNormalized, type RouteRecordName } from 'vue-router'
import { routerList } from './routerList.ts'
import { i18n } from '@/lang/index.ts'
import { userInfo } from '@/store/userInfo.ts'

const { t }: any = i18n.global
const routerHistory = createWebHistory(import.meta.env.BASE_URL)

const router = createRouter({
  history: routerHistory,
  routes: routerList,
})

// 不需要token的页面
const notToken = ['/', '/login', '/404']

// 路由开始发生变化
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  // 不需要token的页面
  if (notToken.includes(to.path)) {
    next()
    return
  }
  // 没有登录的token就退出
  const userInfoStore = userInfo()
  if (!userInfoStore.token) {
    next('/login')
    return
  }
  // 404
  if (!router.hasRoute(to.name as RouteRecordName)) {
    if (to.path.includes('/root')) {
      next('/root/404')
      return
    }
    next('/404')
    return
  }
  next()
})

// 跳转完成之后执行
router.afterEach((to: RouteLocationNormalized) => {
  if (to.meta.title) {
    const name: string = to.meta.title as string
    if (name === '404') {
      document.title = '404'
    } else {
      document.title = t(`LG.menuModel.${name}`)
    }
  }
})

export default router
